package Inkrementor;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Incrementer implements Iterable<Integer>{

	private int from;
	private int to;
	private int step;
	private NumbersIterator iterator;
	
	public Incrementer(int from, int to) {	
	this.from=from;
	this.to=to;
	step=0;
	iterator= new NumbersIterator(this.from, this.to, step);
	}
		
	public static Incrementer in(int from, int to){	
		return new Incrementer(from, to);
	}

	public Incrementer by(int step){	
		iterator.setStep(step);
		return this;
	}
	

	@Override
	public NumbersIterator iterator() {
		// TODO Auto-generated method stub
		return new NumbersIterator(from,to,step);
	}

	private class NumbersIterator implements Iterator<Integer> {

		private int index;
		private boolean start;
		
		public NumbersIterator(int f, int t, int s) {	
		from = f;
		to = t;
		step= s;
		if(step<0 && from<to) {from=t; to=f;  }
		index=from; //System.out.println("index=from =" + index);
		start=true;
		}	
		
		public void setStep(int s){
			step=s;
		}
		
		public int getStep(){	
			if(step==0) step=1;
			if(from>to) step=Math.abs(step)*(-1);
			return step;
		}
		
		public int setIndex() {	
			if(start==true) { start=false;     /*System.out.println("start==true INDEX =" + index);*/  return index; }
			else {	index = index + getStep(); /*System.out.println("start=false INDEX =" + index); */ return index;}
		
		}
		
		public int to(){
			int t=0;
			if(step<0 && from<to) {t=from;}
			else t=to;
			return t;
		}
		
		public int from(){
			int t=0;
			int f=0;
			from=t; 
			to=f;
			if(step>0 && from<to) {from=t; to=f;}
			return t;
		}
		
		
		@Override
		public boolean hasNext() {
			boolean nextExist=false;
			if(getStep()>0 && (index+getStep())<=to())      { nextExist=true; /*System.out.println("nextExist=true, INDEX =" + index);*/  }
			else if(getStep()<0 && (index+getStep())>=to())  { nextExist=true;  /*System.out.println("nextExist=true, INDEX =" + index );*/  }
			return nextExist;
		}

		@Override
		public Integer next() {		
			if (!hasNext()) throw new NoSuchElementException();
			setIndex();
			//System.out.println("return Integer.valueOf(index), INDEX =" + index);
			return Integer.valueOf(index);
		}

		@Override
		public void remove() {
			// TODO Auto-generated method stub

		}

	}
	
	
}


